package org.snail.attendence.service.impl;

import lombok.extern.log4j.Log4j;
import org.snail.activemq.impl.AbAttendencePushServiceImpl;
import org.snail.activemq.impl.AbnormalSenderPushServiceImpl;
import org.snail.activemq.impl.AttendencePushServiceImpl;
import org.snail.attendence.bean.*;
import org.snail.attendence.job.AbnormalRecord;
import org.snail.attendence.mapper.AttendenceMapper;
import org.snail.attendence.mapper.AttendenceMongoMapper;
import org.snail.attendence.service.AttendanceFileOutputService;
import org.snail.base.AttendenceCondition;
import org.snail.common.DateUtils;
import org.snail.common.ExcelUtils;
import org.snail.common.MailUtils;
import org.snail.common.dingding.utils.JedisUtils;
import org.snail.constant.ErrCodeConstant;
import org.snail.constant.MongoCollectionConstant;
import org.snail.employee.bean.EmployeesDO;
import org.snail.employee.mapper.AddressMapper;
import org.snail.employee.mapper.EmployeesMapper;
import org.snail.exception.BaseException;
import org.snail.exception.CommonException;
import org.snail.exception.EmpException;
import org.snail.other.bean.GroupDO;
import org.snail.other.mapper.GroupMapper;
import org.snail.other.service.impl.SendMessageServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.ParseException;
import java.util.*;

/**
 * Created by WJ on 2017/12/12.
 */
@Service
@Log4j
public class AttendanceFileOutputServiceImpl implements AttendanceFileOutputService {

    //考勤信息的文件下载路径
    private String outfilePath = "";

    @Autowired
    private AbnormalRecord abnormalRecord;
    @Autowired
    private AbAttendencePushServiceImpl abAttendencePushService;
    @Autowired
    public SendMessageServiceImpl sendMessageService;
    @Autowired
    public AttendenceMongoMapper attendenceMongoMapper;
    @Autowired
    public AttendencePushServiceImpl attendencePushService;
    @Autowired
    public AttendenceMapper attendenceMapper;
    @Autowired
    private AbnormalSenderPushServiceImpl abnormalSenderPushService;
    @Autowired

    /*
    *   1:"上班忘记打卡",
        2:"下班未打卡",
        3:"严重迟到",
        4:"工作时长小于8小时",
        5:"调休+上班时间小于8小时",
        12:"上下班均未打卡",
        13:"请假后上下班缺卡"
    * */
    private static Map<Integer,String> map=new HashMap<Integer,String>();
    public AttendanceFileOutputServiceImpl(){
        map.put(1,"上班忘记打卡");
        map.put(2,"下班未打卡");
        map.put(3,"严重迟到");
        map.put(4,"工作时长小于8小时");
        map.put(5,"调休+上班时间小于8小时");
        map.put(12,"上下班均未打卡");
        map.put(13,"请假后上下班缺卡");
    }

    /**
     *   考勤不需要预览功能
     */
    public List<AbnormalAttendanceDTO> getAttendanceList(CommonsMultipartFile file, HttpServletRequest request) throws BaseException, ParseException {
        String excelName = file.getOriginalFilename();
        String outfileName = "out" + file.getOriginalFilename();
        String pathHome = request.getSession().getServletContext().getRealPath("upload");
        outfilePath = pathHome + "/" + outfileName;
        log.info("fileName：" + excelName);
        List<AliWorkDTO> attOriginList =  ExcelUtils.getListFromExcel(file, pathHome, AliWorkDTO.class, 4);
        List<AbnormalAttendanceDTO> abnormalAttendanceDTOS = getAbnormalAttendanceList(attOriginList);
        ExcelUtils.writeToExcel(outfilePath, abnormalAttendanceDTOS, 0, "异常考勤数据");
        return abnormalAttendanceDTOS;
    }

    public List<AbnormalAttendanceDTO> getAbnormalAttendanceList(List<AliWorkDTO> aliWorkDTOS) throws BaseException, ParseException {
        if (null == aliWorkDTOS ) {
            throw new CommonException(ErrCodeConstant.ILLEGAL_PARAM, "分析考勤异常时，传来的考勤列表参数为空！");
        }
        List empAbnormalsMap = abnormalRecord.getAbnormalAttendance(aliWorkDTOS);

        return empAbnormalsMap;
    }


    public void sendMessageToDing(List<AbnormalAttendanceDTO> abnormalAttendanceList) throws Exception {
        AbAttendenceMongo abAttendenceMongo = new AbAttendenceMongo();
        abAttendenceMongo.setAbnormalAttendanceDTOList(abnormalAttendanceList);
        abnormalSenderPushService.push(abAttendenceMongo);
    }

    /**
     * 下载考勤信息附件
     * @return entity Excel表格
     * @throws IOException  文件IO流异常
     */
//    @RequestMapping("/attendanceDownLoad")
    public ResponseEntity<byte[]> download(String strPath) throws IOException {
        File file = null;
        file = new File(strPath);
        ResponseEntity<byte[]> entity = getResponseEntity(file);
        return entity;
    }
    public ResponseEntity<byte[]> download() throws IOException {
        File file = null;
        file = new File(outfilePath);
        ResponseEntity<byte[]> entity = getResponseEntity(file);
        return entity;
    }
    private ResponseEntity<byte[]> getResponseEntity(File file) throws IOException {
        byte[] body;
        InputStream is = new FileInputStream(file);
        body = new byte[is.available()];
        is.read(body);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "attchement;filename=" + file.getName());
        HttpStatus statusCode = HttpStatus.OK;
        ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);
        return entity;
    }

    /**
     * 发送邮件
     */
    //TODO: 将异常数据也发送至邮箱中
    public void sendEmail(){
        MailUtils.sendEmail(outfilePath);
    }

    /**
     * 将传入的map改格式传入mongoDB
     */
    private void setAttList2Mongo(Map<GroupDO, Map<EmployeesDO, List<AbnormalAttendanceDTO>>> abnormaoAttendenceMap) throws CommonException {
        for (Map.Entry<GroupDO, Map<EmployeesDO, List<AbnormalAttendanceDTO>>> attendenceEntry : abnormaoAttendenceMap.entrySet()){
            AbAttendenceMongo abAttendenceMongo = new AbAttendenceMongo();
            abAttendenceMongo.setInsertTime(DateUtils.getCurrentTime(8));
            abAttendenceMongo.setGroupDO(attendenceEntry.getKey());
            for (Map.Entry<EmployeesDO, List<AbnormalAttendanceDTO>> listEntry : attendenceEntry.getValue().entrySet()) {
                abAttendenceMongo.setAbnormalAttendanceDTOList(listEntry.getValue());
                abAttendenceMongo.setEmployeesDO(listEntry.getKey());
                abAttendencePushService.push(abAttendenceMongo);             //消息队列
             }
        }

    }

}
